package com.deerblock.invokenative;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.NonNull;

import com.deerblock.Constant;
import com.deerblock.LoginActivity;
import com.deerblock.MainActivity;
import com.deerblock.config.AuthPageConfig;
import com.deerblock.config.BaseUIConfig;
import com.deerblock.config.LoginCallback;
import com.deerblock.config.ResponseStruct;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.google.gson.Gson;
import com.umeng.umverify.UMResultCode;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMPreLoginResultListener;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;


public class VerifyModule extends ReactContextBaseJavaModule implements ActivityEventListener {
  private static final String TAG = VerifyModule.class.getSimpleName();
  private static boolean sdkAvailable = true;
  private UMVerifyHelper mVerifyHelper;
  private static  AuthPageConfig mUIConfig;
  private String token;
  private final ReactApplicationContext reactContext;
  private Activity mActivity;
  private LoginCallback loginCallback;
  private Boolean invoked = false;
  public VerifyModule(ReactApplicationContext reactContext) {
    super(reactContext);
    reactContext.addActivityEventListener((ActivityEventListener) this);
    this.reactContext = reactContext;
    this.checkAvailable();
  }



  private void checkAvailable(){
    UMTokenResultListener mCheckAvailableListener = new UMTokenResultListener() {
      @Override
      public void onTokenSuccess(String s) {
        UMTokenRet tokenRet = null;
        tokenRet = UMTokenRet.fromJson(s);
        Log.i(TAG, "checkEnvAvailable" + s);
        if (UMResultCode.CODE_ERROR_ENV_CHECK_SUCCESS.equals(tokenRet.getCode())) {
          accelerateLoginPage();
        }
      }

      @Override
      public void onTokenFailed(String s) {
        Log.e("TAG", "checkEnvAvailable：" + s);
        sdkAvailable = false;
      }
    };
    mVerifyHelper = UMVerifyHelper.getInstance(this.reactContext, mCheckAvailableListener);
    mVerifyHelper.setAuthSDKInfo(Constant.UMAppScrect);
    mVerifyHelper.checkEnvAvailable(UMVerifyHelper.SERVICE_TYPE_LOGIN);
  }

  /**
   * 在不是一进app就需要登录的场景 建议调用此接口 加速拉起一键登录页面
   * 等到用户点击登录的时候 授权页可以秒拉
   * 预取号的成功与否不影响一键登录功能，所以不需要等待预取号的返回。
   */
  private void accelerateLoginPage() {
    mVerifyHelper.accelerateLoginPage(5000, new UMPreLoginResultListener() {
      @Override
      public void onTokenSuccess(String s) {
        Log.e(TAG, "预取号成功: " + s);
      }

      @Override
      public void onTokenFailed(String s, String s1) {
        Log.e(TAG, "预取号失败：" + ", " + s1);
      }
    });
  }

  @NonNull
  @Override
  public String getName() {
    return "UMverifyModule";
  }

  @ReactMethod
  public void login(Callback success,Callback fail){
    mActivity = reactContext.getCurrentActivity();

    loginCallback = new LoginCallback() {
      @Override
      public void onSuccess(String data) {
        success.invoke(data);
      }

      @Override
      public void onFail() {
        fail.invoke();
      }
    };

    if(invoked) return;
    invoked = true;
    if(!sdkAvailable){
      Intent pIntent = new Intent(mActivity,LoginActivity.class);
      mActivity.startActivityForResult(pIntent,1002);
      return;
    }

    getLoginToken(5000);

    //TODO 调用token登录借口
  }

  private void getLoginToken(int timeout){
    mUIConfig = BaseUIConfig.init(Constant.UI_TYPE.DIALOG_BOTTOM, mActivity, mVerifyHelper);
    mUIConfig.configAuthPage();
    UMTokenResultListener mTokenResultListener = new UMTokenResultListener() {
      @Override
      public void onTokenSuccess(String s) {
        UMTokenRet tokenRet;
        try {
          tokenRet = UMTokenRet.fromJson(s);
          if (UMResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
            Log.i(TAG, "唤起授权页成功：" + s);

          }
          if (UMResultCode.CODE_GET_TOKEN_SUCCESS.equals(tokenRet.getCode())) {
            Log.i(TAG, "获取token成功：" + s);
            token = tokenRet.getToken();
            mUIConfig.release();
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      @Override
      public void onTokenFailed(String s) {
        Log.e(TAG, "获取token失败：" + s);
        Intent pIntent = new Intent(mActivity, LoginActivity.class);
        mActivity.startActivityForResult(pIntent, 1002);
        mVerifyHelper.quitLoginPage();
        mUIConfig.release();
      }
    };
    mVerifyHelper.setAuthListener(mTokenResultListener);
    mVerifyHelper.getLoginToken(this.reactContext,timeout);
  }

  @Override
  public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    Log.i(TAG,resultCode+"");
    invoked = false;
    if(requestCode == 1002){
      if(resultCode == 1){
        Log.i(TAG,data.getStringExtra("result"));
        loginCallback.onSuccess(data.getStringExtra("result"));
      }else{
        loginCallback.onFail();
      }

    }
  }

  @Override
  public void onNewIntent(Intent intent) {
    Log.i(TAG,intent+"");
  }
}
